# -*- coding: utf-8 -*-

import json
import logging

from django.utils.decorators import method_decorator
from django.utils.encoding import smart_unicode
from django.views.generic import TemplateView

from common.account.db import account as account_db
from common.cache import redis_cache
from common.platform.metis import handler as metis_handler
from common.platform.metis import metis_api
from common.utils.api import check_params, token_required
from common.utils.decorator import response_wrapper
from common.utils.export import gen_filename, redirect_to_file
from common.utils.tz import utc_to_local_str

_LOGGER = logging.getLogger(__name__)

PLATFORM = 'metis'


class MetisConsoleView(TemplateView):

    def get(self, req):
        """获取Metis水池/抽水率
        """
        query_dct = req.GET.dict()
        game_id = query_dct['game_id']
        status, data = metis_api.get_pool(game_id)
        now_rate, now_pool = data['pool_refund'], data['pool_money']
        return {'now_rate': now_rate, 'now_pool': now_pool}

    def post(self, req):
        """设定Metis游戏每日分析配置：人工增减抽水金额/预期抽水率
        """
        query_dct = json.loads(req.body)
        game_id = query_dct.get('game_id')
        control_rate = query_dct.get('control_rate', 0)
        control_rate = float(control_rate) / 100
        control_pool = query_dct.get('control_pool', 0)
        dct = metis_handler.set_pool(game_id, control_rate, control_pool)
        return dct

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(MetisConsoleView, self).dispatch(*args, **kwargs)


class MetisDailyBetView(TemplateView):

    def get(self, req):
        """获取Metis单日投注上限金额
        """
        amount = redis_cache.get_daily_bet(PLATFORM)
        return {'amount': amount}

    def post(self, req):
        """设定Metis单日累计投注上限金额
        """
        query_dct = json.loads(req.body)
        check_params(query_dct,
                     required_params=['amount'])
        amount = int(query_dct['amount'])

        redis_cache.set_daily_bet(PLATFORM, amount)
        return {}

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(MetisDailyBetView, self).dispatch(*args, **kwargs)


class MetisForbiddenView(TemplateView):

    def get(self, req):
        """获取Metis禁止登入名单
        """
        query_dct = req.GET.dict()
        export = query_dct.pop('$export', None)
        uids = redis_cache.get_metis_risk_uids(PLATFORM, 'forbidden')

        if export:  # 导出记录信息
            resp_items = []
            filename = gen_filename('{}_forbidden'.format(PLATFORM))
            cn_header = [u'用户ID', u'手机号', u'注册时间']
            for i in uids:
                uid = int(i)
                account = account_db.get_account(uid)
                resp_items.append([uid, account.phone, utc_to_local_str(account.created_at)])
                return redirect_to_file(resp_items, cn_header, filename)
        return {'list': list(uids), 'page': 1, 'size': len(uids),
                'stock': [], 'total_count': len(uids)}

    def post(self, req):
        """设定Metis禁止登入名单
        """
        uids = json.loads(smart_unicode(req.body))
        try:
            redis_cache.add_metis_risk_uids(PLATFORM, 'forbidden', *uids)
        except:
            pass
        return {}

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(MetisForbiddenView, self).dispatch(*args, **kwargs)


class MetisPassView(TemplateView):

    def get(self, req):
        """获取Metis测试登入名单
        """
        query_dct = req.GET.dict()
        export = query_dct.pop('$export', None)
        uids = redis_cache.get_metis_risk_uids(PLATFORM, 'pass')

        if export:  # 导出记录信息
            resp_items = []
            filename = gen_filename('{}_pass'.format(PLATFORM))
            cn_header = [u'用户ID', u'手机号', u'注册时间']
            for i in uids:
                uid = int(i)
                account = account_db.get_account(uid)
                resp_items.append([uid, account.phone, utc_to_local_str(account.created_at)])
                return redirect_to_file(resp_items, cn_header, filename)
        return {'list': list(uids), 'page': 1, 'size': len(uids),
                'stock': [], 'total_count': len(uids)}

    def post(self, req):
        """设定Metis测试登入名单
        """
        uids = json.loads(smart_unicode(req.body))
        try:
            redis_cache.add_metis_risk_uids(PLATFORM, 'pass', *uids)
        except:
            pass
        return {}

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(MetisPassView, self).dispatch(*args, **kwargs)
